package com.jiawei.jwboot.thymeleaf;

import annotation.component.Component;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import annotation.component.di.Value;
import common.Template;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import utils.ObjectUtil;

import java.io.IOException;
import java.util.Map;

/**
 * @author : willian fu
 * @version : 1.0
 */
@Component
public class ThymeleafTemplate implements Template {

    /**
     * 模板路径配置， 默认templates
     */
    @Value("jwboot.thymeleaf.templates.path")
    private String templatePath;

    @Value("jwboot.thymeleaf.templates.catch-time")
    private Long catchTime;

    @Value("jwboot.thymeleaf.templates.catch-able")
    private Boolean catchAble;

    private static TemplateEngine templateEngine;

    private static ServletContext context;

    public TemplateEngine templateEngineInit(ServletContext servletContext){
        context = servletContext;
        ServletContextTemplateResolver templateResolver =
                new ServletContextTemplateResolver(servletContext);
        // HTML is the default mode, but we set it anyway for better understanding of code
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // This will convert "home" to "/WEB-INF/templates/home.html"
        templateResolver.setPrefix(ObjectUtil.setDefault(templatePath, "/templates/"));
        templateResolver.setSuffix(ObjectUtil.setDefault(null, ".html"));
        // Template cache TTL=1h. If not set, entries would be cached until expelled
        templateResolver.setCacheTTLMs(ObjectUtil.setDefault(catchTime,  3600000L));
        templateResolver.setCacheable(ObjectUtil.setDefault(catchAble, true));
        templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

    /**
     * 获取模板引擎
     * @return
     */
    public TemplateEngine getTemplateEngine(){
        ObjectUtil.notNullMsg(templateEngine, "thymeleaf模板引擎没有初始化，请先调用templateEngineInit");
        return templateEngine;
    }

    /**
     * 解析模板
     * @param request 请求
     * @param response 响应
     * @param templateName 模板名
     * @param params 参数名
     * @throws IOException 模板写出异常
     */
    public void resolveTemplate(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> params) throws IOException {
        if (!ObjectUtil.isNotNull(context)){
            this.templateEngineInit(request.getServletContext());
        }
        WebContext ctx = new WebContext(request, response, context, request.getLocale());
        ctx.setVariables(params);
        templateEngine.process(templateName, ctx, response.getWriter());
    }
}
